package com.example.skytakeoutserver.service

import lombok.RequiredArgsConstructor
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate
import org.springframework.data.r2dbc.repository.Query
import org.springframework.r2dbc.core.DatabaseClient
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import java.time.LocalDateTime

@Service
@RequiredArgsConstructor
class OrderService(
    private val r2dbcEntityTemplate: R2dbcEntityTemplate,
    private val databaseClient: DatabaseClient
) {
    /**
     * 计算订单的营业额
     */
    fun sumByMap(
        status: Int,
        begin: LocalDateTime,
        end: LocalDateTime
    ): Mono<Double> {
        val sqlBuilder = StringBuilder(
            "select sum(amount) from orders where 1=1"
        )

        status.let {
            sqlBuilder.append(" and status = :status")
        }

        begin.let {
            sqlBuilder.append(" and order_time >= :begin")
        }
        end.let {
            sqlBuilder.append(" and order_time <= :end")
        }

        var spec = databaseClient.sql(sqlBuilder.toString())

        status.let {
            spec = spec.bind("status", it)
        }
        begin.let {
            spec = spec.bind("order_time", it)
        }
        end.let {
            spec = spec.bind("order_time", it)
        }

        return spec
            .map { row ->
                row.get("sum(amount", Double::class.java)
            }
            .one()
            .map { sum -> sum ?: 0.0 }// 如果sum为null,直接返回0.0
            .onErrorResume {
                // 错误也返回一个默认值。避免终止流程
                Mono.just(0.0)
            }
    }

}